package xin.nick.common.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import xin.nick.common.entity.http.RequestWrapper;
import xin.nick.common.entity.http.ResponseWrapper;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Nick
 * @since 2022/7/26/026
 */
@Slf4j
public class HttpServletRequestWrapperFilter implements Filter {


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        // 包装request
        ServletRequest requestWrapper = null;
        if(servletRequest instanceof HttpServletRequest) {
            requestWrapper = new RequestWrapper((HttpServletRequest) servletRequest);
        }
        if(requestWrapper == null) {
            requestWrapper = servletRequest;
        }

        // 包装response
        ServletResponse responseWrapper = null;
        if(servletResponse instanceof HttpServletResponse) {
            responseWrapper = new ResponseWrapper((HttpServletResponse)servletResponse);
        }
        if(responseWrapper == null) {
            responseWrapper = servletResponse;
        }

        filterChain.doFilter(requestWrapper, responseWrapper);

    }
}

